<template>
    <div class="app-container">
        <levelbar></levelbar>
        <div class="form-box" v-loading='loading'>
          <div class="form-title">新增学生</div>
            <el-form :model="formList" ref="formList" label-width="80px" class="form">
                <div class="form-item">
                    <div class="form-item-title">
                        <span>基本信息</span>
                    </div>
                    <div class="form-content">
                        <el-row :gutter="21">
                          <el-col :span="12">
                              <el-form-item label="学生姓名" prop="studentName" :rules="name">
                                <el-popover placement="top-start" trigger="focus" content="最大输入12个汉字">
                                  <el-input style="width:95%" slot="reference" :maxlength="12" placeholder="请输入学生姓名" v-model="formList.studentName"></el-input>
                                </el-popover>
                              </el-form-item>
                          </el-col>
                          <el-col :span="12">
                              <el-form-item label="性别" prop="sex">
                                  <el-radio-group v-model="formList.sex">
                                      <el-radio label="0">男</el-radio>
                                      <el-radio label="1">女</el-radio>
                                  </el-radio-group>
                              </el-form-item>
                          </el-col>
                      </el-row>
                      <el-row :gutter="21">
                          <el-col :span="12">
                              <el-form-item label="学籍号" prop="schoolRoll" :rules="schoolRoll">
                                  <el-popover placement="top-start" trigger="focus" content="长度在20个字符以内。">
                                    <el-input placeholder="请输入学籍号" slot="reference" :maxlength="20" v-model="formList.schoolRoll" style="width:95%;"></el-input>
                                  </el-popover>
                              </el-form-item>
                          </el-col>
                          <el-col :span="12">
                              <el-form-item label="出生日期" prop="birthday" >
                                  <el-date-picker :editable="false" style="width:95%" v-model="formList.birthday" type="date" placeholder="选择日期" :picker-options="pickerOptions0">
                                  </el-date-picker>
                              </el-form-item>
                          </el-col>
                      </el-row>
                    </div>
                </div>
                <div class="form-item">
                    <div class="form-item-title">
                        <span>家长信息</span>
                    </div>
                    <div class="form-content">
                        <el-row :gutter="21" v-for="(item, index) in formList.contactWayList" :key="index">
                          <el-col :span="12">
                              <el-form-item :label="'联系人 ' + (index + 1)" :prop="'contactWayList.' + index + '.phone'" :rules="index==0?namephone:otherContactWay">
                                <el-popover placement="top-start" trigger="focus" content="请输入11位手机号">
                                  <el-input style="width:95%" slot="reference" :maxlength="11"  placeholder="请输入手机号" v-model="item.phone" ></el-input>
                                </el-popover>
                              </el-form-item>
                          </el-col>
                          <el-col :span="1" v-if="index != 0">
                                <el-button type="text" class="delBtn" @click="removeContactWay(index)"><i class="el-icon-delete"></i></el-button>
                          </el-col>
                        </el-row>
                        <el-button v-if="formList.contactWayList.length < 5" type="text" @click="addContactWay" class="addBtn btn-success"><i class="el-icon-plus"></i> 继续添加</el-button>
                    </div>
                </div>
                <div class="form-item">
                  <div class="box">
                    <el-button @click="cancel">取消</el-button>
                    <el-button @click="submitForm('formList')" type="primary">立即创建</el-button>
                  </div>
                </div>
            </el-form>
        </div>
    </div>
</template>
<script>
import Levelbar from "../layout/Levelbar";
import { addStudentIntoClass } from "api/classAll";
import validate from '@/utils/validate';
export default {
  name:"addNewStudent",
  components: { Levelbar },
  data() {
    return {
      loading: false,
      formList: {
        studentName: "",
        sex: "0",
        schoolRoll: "",
        birthday: "",
        phone: "",
        contactWayList: [{
            phone: ''
        }]
      },
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e7;
        }
      },
      name: [
        { required: true, message: "请输入内容", trigger: "blur" },
        { min: 0, max: 12, message: "请输入合法的内容", trigger: "blur" }
      ],
      nameRoll: [
        { message: "请输入内容", required: true },
        { message: "请输入合法学籍", trigger: "blur", pattern: /^\d{0,20}$/ }
      ],
      namephone: [
        ...validate.phoneRequired()
      ],
      otherContactWay: [
        ...validate.phone()
      ],
      nameBirthday: [
        { type: "date", required: true, message: "请选择日期", trigger: "change" }
        // { message: "请输入内容", required: true },
        // {
        //   message: "请输入合法的生日",
        //   trigger: "blur",
        //   pattern: /^(19|20)\d{2}-(1[0-2]|0?[1-9])-(0?[1-9]|[1-2][0-9]|3[0-1])$/
        // }
      ],
      resource: { required: true, message: "请选择性别", trigger: "change" },
      schoolRoll:[
        { pattern: /^[A-Za-z0-9]+$/, message: "只允许输入数字和字母" },
        { min: 1, max: 20, message: "长度在20个字符以内", trigger: "blur" }
      ]
    };
  },
  methods: {
    addContactWay() {
        this.formList.contactWayList.push({
          phone: ''
        });
    },
    removeContactWay(index) {
        if (index !== -1) {
          this.formList.contactWayList.splice(index, 1);
        }
    },
    formatDate(str) {
      if (str) {
        let Year = null,
          Month = null,
          date = null;
        Year = ~~str.getFullYear();
        Month = ~~str.getMonth() + 1;
        date = ~~str.getDate();
        return `${Year}-${Month + "".length > 1
          ? Month
          : "0" + Month}-${date.length > 1 ? date : "0" + date}`;
      }
    },
    submitForm(formList) {
      let phoneArray = [];
      this.formList.contactWayList.forEach(item => {
          if(item.phone) {
              phoneArray.push(item.phone);
          }
      });
      const items = new Set(phoneArray);
      if(items.size != phoneArray.length) {
          this.$message.error('联系人号码重复');
          return;
      }
      this.$refs[formList].validate(valid => {
        if (valid) {

          let phones = [];
          this.formList.phone = this.formList.contactWayList[0].phone;
          if(this.formList.contactWayList.length >1) {
              this.formList.contactWayList.forEach(function(item, index) {
                  if(index != 0 && item.phone) {
                      phones.push(item.phone);
                  }
              });
          }
          this.$confirm('确认新增学生吗?', ' ', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: ' '
        }).then(() => {
          this.loading = true;
          addStudentIntoClass(
            this.formList.studentName,
            this.formList.sex,
            this.formList.schoolRoll,
            !this.formatDate(this.formList.birthday)
              ? ""
              : this.formatDate(this.formList.birthday),
            this.formList.phone,
            this.$route.params.classId,
            this.$route.params.schoolId,
            phones
          ).then(data => {
            this.loading = false;
            this.$router.push({
              path: `/classStudent/studentList/${this.$route.params.id}`
            });
            this.$message({
              message: "新增成功！",
              type: "success"
            });
            this.$store.dispatch('UpdateCache');
          }).catch(() =>{
              this.loading = false;
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });          
        });
          
        } else {
          return false;
        }
      });
    },
    cancel() {
      this.$router.go(-1);
    }
  }
};
</script>
<style lang="scss" scoped>
.app-container {
  position: relative;
  padding: 20px 20px 10px;
  $bgcolor: #fff;

  @mixin showTitle() {
    background: $bgcolor;
    box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.1);
    -webkit-box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.1);
  }
    .delBtn {
        font-size: 20px;
        color:#999;
    }
    .addBtn{
        margin-left:80px;
        font-size:14px;
        color:#ff5e2c;
    }
  .form-box {
    padding: 0px 50px;
    @include showTitle();
    .form-title {
      text-align: center;
      font-size: 18px;
      color: #333;
      height: 72px;
      line-height: 72px;
      font-weight: bold;
      border-bottom: 1px solid #ddd;
      font-family: Microsoft YaHei;
    }
    .form {
      .form-item {
        .form-item-title {
          margin: 40px 0;
          font-size: 14px;
          color: #333;
          line-height: 14px;
          border-left: 4px solid #ff5e2c;
          text-indent: 16px;
        }
        .form-content {
          margin-left: 17px;
        }
        .item {
          margin-bottom: 20px;
        }
        .back {
          margin-top: 20px;
        }
        .footer {
          //float: right;
          text-align: center;
          margin-top: 60px;
        }
        .title-way {
          padding-right: 15px;
        }
        .control {
          text-align: right;
        }
      }
    }
  }
}
.box {
  text-align: center;
  padding: 60px 0;
}
</style>
